<?php
//微信用户相关

namespace App\Http\Controllers;

use App\Repositories\AdminRepository;
use App\Repositories\StrategyRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Traits\BaseHttp;
use App\Models\StrategyModel;
use App\Models\AdminModel;
use App\Services\AdminService;

class AdminController extends BaseController
{
    public function login (Request $request, AdminRepository $adminRepository)
    {
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        $res = AdminService::login($username, $password);
        if ($res['errcode']) {
            return $this->error(401, $res['errmsg']);
        }

        return $this->success($res['data']);
    }

    /**
     * 登出
     * @param  Request  $request
     * @return JsonResponse
     */
    public function logout(Request $request)
    {
        $user = $request->user();

        // 撤销所有令牌...
        $user->tokens()->delete();

        return $this->success();
    }
    /**
     * @param Request $request
     * @param AdminRepository $adminRepository
     * @return \Illuminate\Http\JsonResponse
     */
    public function list (Request $request, AdminRepository $adminRepository)
    {
        $params = $request->all();
        $list = $adminRepository->getList($params);
        return $this->success($list);
    }

    public function info () {
        return $this->success([
            'name' => '果志天',
            'avatar' =>
            'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTL9zZaicS9y1JNSTiaKXPbWbDuemY7ucCyNnJa2YmSTLr1bmvlpUXELh995Vl6sMb8ZO27uENialrpxQ/132',
            'email' => 'guozhit@qq.com'
        ]);
    }

    /**
     * @param Request $request
     * @param AdminRepository $adminRepository
     * @return \Illuminate\Http\JsonResponse
     */
    public function save (Request $request, AdminRepository $adminRepository)
    {
        $allParams = $request->all();
        $rst = $adminRepository->addOrUpdate($allParams);
        if ($rst) {
            return $this->success();
        }
        return $this->error(510, '未知错误，请稍后再试');
    }

    /**
     * @param Request $request
     * @param AdminRepository $adminRepository
     * @return \Illuminate\Http\JsonResponse
     */
    public function savePassword (Request $request, AdminRepository $adminRepository)
    {
        $allParams = $request->all();
        if ($allParams['password'] !== $allParams['comfirmPassword']) {
            return $this->error(410, '两次密码不一致');;
        }
        $rst = $adminRepository->savePassword($allParams);
        if ($rst) {
            return $this->success();
        }
        return $this->error(510, '未知错误，请稍后再试');
    }
}
